package com.appspot.diasporajava.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.appspot.diasporajava.controller.MainController;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

@Component
public class WebsiteVisitor {
	private Log log = LogFactory.getLog(MainController.class);

	private URLFetchService fetcher;

	public WebsiteVisitor() {
		fetcher = URLFetchServiceFactory.getURLFetchService();
	}

	private byte[] open(String address) {
		URL url;
		try {
			url = new URL(address);
			HTTPResponse targetResponse = fetcher.fetch(url); // Error
			return targetResponse.getContent();
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return null;
		}
	}

	public String visit(String address) {

		return new String(open(address));
	}

	public InputStream getInputStream(String address) {
		return new ByteArrayInputStream(open(address));
	}
}
